<template>
	<div class="Login">
		<div class="content">
			<img src="../assets/img/title.png" alt class="title-pic" v-if="lang == '0' || lang == '1'" />
			<img src="../assets/img/title_en.png" alt class="title-pic" v-else />
			<p class="msg">A-MIS Ver.7 for Web</p>
			<div class="pic-login-box">
				<div class="title-top">{{ $t("message.login.title") }}</div>
				<el-input :placeholder="$t('message.login.userName')" prefix-icon="el-icon-user" v-model="userName"
					class="ipt"></el-input>
				<el-input :placeholder="$t('message.login.psw')" prefix-icon="el-icon-lock" v-model="passWord"
					show-password class="ipt" type="password"></el-input>
				<div class="checkbox-view">
					<el-checkbox v-model="checked">{{
						$t("message.login.automaticLogon")
					}}</el-checkbox>
					<!-- <span class="forget">{{$t('message.login.forgetPsw')}}？</span> -->
				</div>
				<button class="login-btn" @click="login" v-loading="loading" element-loading-spinner="el-icon-loading"
					element-loading-background="rgba(230, 1, 19, 0.8)">
					{{ $t("message.login.login") }}
				</button>
				<div class="lang-view">
					<el-dropdown>
						<span>{{ $t("message.language.name") }}</span>
						<!-- <el-dropdown-menu slot="dropdown">
							<el-dropdown-item @click.native="langChange('0')">
								日本語
							</el-dropdown-item>
							<el-dropdown-item @click.native="langChange('2')">
								English
							</el-dropdown-item>
							<el-dropdown-item @click.native="langChange('1')">
								中文
							</el-dropdown-item>
						</el-dropdown-menu> -->
					</el-dropdown>
				</div>
			</div>
		</div>

		<!-- change pwd -->
		<el-dialog :title="$t('message.login.changePwd')" :visible.sync="showChangePWDDialog" width="30%"
			:append-to-body="true" :close-on-click-modal="false">
			<el-form label-position="right" label-width="150px" :model="formLabelAlign" :rules="rules"
				ref="formLabelAlign">
				<el-form-item :label="$t('message.config_dialog.title_2')" prop="pass">
					<el-input v-model="formLabelAlign.pwd" size="small"
						:type="formLabelAlign.showOnce ? 'text' : 'password'" autocomplete="off">
						<el-image :src="formLabelAlign.showOnce ? uncheckImg : checkImg
							" slot="suffix" alt="" style="margin-top: 8px; width: 25px; height: 25px" @click="
								formLabelAlign.showOnce =
								!formLabelAlign.showOnce
								"></el-image>
					</el-input>
				</el-form-item>
				<el-form-item :label="$t('message.config_dialog.title_3')" prop="checkPass">
					<el-input v-model="formLabelAlign.checkPass" size="small"
						:type="formLabelAlign.showTwice ? 'text' : 'password'" autocomplete="new-password">
						<el-image :src="formLabelAlign.showTwice ? uncheckImg : checkImg
							" slot="suffix" alt="" style="margin-top: 8px; width: 25px; height: 25px" @click="
								formLabelAlign.showTwice =
								!formLabelAlign.showTwice
								"></el-image>
					</el-input>
				</el-form-item>
			</el-form>
			<div class="divider" style="margin-bottom: 22px" />
			<span slot="footer" class="dialog-footer">
				<el-button size="small" @click="cancelClick()">{{
					$t("message.public.cancel")
				}}</el-button>
				<el-button type="primary" size="small" @click="changeOrgUserPwdApi()">{{ $t("message.public.confirm")
					}}</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import { setLocalStorage, getLocalStorage } from "../utils/storage";
import { setCookie, getCookie, removeCookie } from "../utils/cookie";
import { login, requestToken, changeOrgUserPwd, GetDBLan } from "../api/api";
import md5 from "js-md5";
import BASE from '@/utils/base'
// 导出模块
export default {
	// 模块名字
	name: "Login",
	// 模块数据
	data() {
		var validatePass = (rule, value, callback) => {
			if (
				!/^(?![A-Za-z]+$)(?![A-Z\d]+$)(?![A-Z\W]+$)(?![a-z\d]+$)(?![a-z\W]+$)(?![\d\W]+$)\S{6,20}$/.test(
					this.formLabelAlign.pwd
				)
			) {
				callback(
					new Error(this.$t("message.userPageTable.rules.checkPsd"))
				);
			} else {
				if (
					this.formLabelAlign.pwd !== "" &&
					/^(?![A-Za-z]+$)(?![A-Z\d]+$)(?![A-Z\W]+$)(?![a-z\d]+$)(?![a-z\W]+$)(?![\d\W]+$)\S{6,20}$/.test(
						this.formLabelAlign.pwd
					)
				) {
					this.$refs.formLabelAlign.validateField("checkPass");
				}
				callback();
			}
		};
		var validatePass2 = (rule, value, callback) => {
			if (value !== this.formLabelAlign.pwd) {
				callback(
					new Error(
						this.$t("message.userPageTable.rules.checkPsdTip")
					)
				);
			} else {
				callback();
			}
		};
		//数据
		return {
			path: '',
			macName: '',
			macType: 1,
			pltCode: 9,
			checkImg: require("@/assets/img/icon_but_hide_dark@2x.png"),
			uncheckImg: require("@/assets/img/icon_but_display_dark@2x.png"),
			userName: "",
			passWord: "",
			checked: false,
			loading: false,

			lang: getLocalStorage("lang"),

			showChangePWDDialog: false,

			formLabelAlign: {
				pwd: "",
				checkPass: "",
				showOnce: false,
				showTwice: false,
			},

			rules: {
				pass: [
					{
						validator: validatePass,
						trigger: "blur",
						required: true,
					},
				],
				checkPass: [
					{
						validator: validatePass2,
						trigger: "blur",
						required: true,
					},
				],
			},
		};
	},
	// 注册组件
	components: {},
	// 监听指定值，只有指定值变化，才会触发
	watch: {},
	// 里面的函数只有调用才会执行（实时计算）里面是定义的方法
	methods: {
		async setDefaultLang() {
			// Option / GetDBLan 获取db语言
			// 返回结果中的data：1 = 日语 0 = 英语
			let dataJson = {};
			let res = await GetDBLan(dataJson);
			let r = res.data.data == 1 ? 0 : 2;
			// let r = 2;
			this.langChange(r)
		},
		login() {
			this.loading = true;
			let md5Psw = md5(this.passWord.trim());
			requestToken({
				username: this.userName.trim(),
				password: md5Psw,
				IsCheckPwdErrCnt: true
			})
				.then((res) => {
					if (res.data.code == 1002) {
						this.loading = false;
						this.$alert(this.$t("message.login.tipPsw"), '', {
							confirmButtonText: 'OK',
							type: 'warning',
						});
						return;
					} else if (res.data.code == 1003) {
						this.$alert(this.$t("message.login.noUser"), '', {
							confirmButtonText: 'OK',
							type: 'warning',
						});
						return;
					} else if (res.data.code == 1004) {
						this.loading = false;
						this.$alert(this.$t("message.login.waitTip"), '', {
							confirmButtonText: 'OK',
							type: 'warning',
						});
						return;
					} else if (res.data.code != 0) {
						this.loading = false;
						this.$alert(res.data.msg, '', {
							confirmButtonText: 'OK',
							type: 'warning',
						});
						return;
					}
					if (res.data.data.isChangePwd == 2) {
						this.loading = false;
						this.showChangePWDDialog = true;
						return;
					}

					if (res.data.code == -310) {
						this.loading = false;
						this.$message({
							type: 'error',
							message: res.data.msg
						})
					}
					if (res.data.code == 0) {
						setLocalStorage("userChecked", this.checked);
						sessionStorage.token = res.data.data;
						setLocalStorage("token", res.data.data);
						setCookie("token", res.data.data, 7);
						login({
							UserName: this.userName.trim(),
							Password: md5(this.passWord.trim()),
						})
							.then((res) => {
								this.loading = false;
								if (res.data.code == 1002) {
									this.$alert(this.$t("message.login.tipPsw"), '', {
										confirmButtonText: 'OK',
										type: 'warning',
									});
									return;
								} else if (res.data.code == 1003) {
									this.$alert(this.$t("message.login.noUser"), '', {
										confirmButtonText: 'OK',
										type: 'warning',
									});
									return;
								} else if (res.data.code == 1004) {
									this.$alert(this.$t("message.login.waitTip"), '', {
										confirmButtonText: 'OK',
										type: 'warning',
									});
									return;
								} else if (res.data.code != 0) {
									this.$alert(res.data.msg, '', {
										confirmButtonText: 'OK',
										type: 'warning',
									});
									return;
								}

								// res.data.data.isChangePwd = 2;
								// // 默认isChangePwd = 2， 1不需要更改密码  2需要更改密码
								// res.data.data.isChangePwd = 2;
								if (res.data.data.isChangePwd == 2) {
									this.showChangePWDDialog = true;
									return;
								}

								setLocalStorage("activeClass", 0);
								setLocalStorage(
									"accType",
									res.data.data.accType
								);
								//	 存储多个用户id
								if (!getLocalStorage("userArrId")) {
									setLocalStorage("userArrId", []);
								}
								let userArrId = getLocalStorage("userArrId");
								userArrId.push(res.data.data.id);
								setLocalStorage("userArrId", userArrId);

								setLocalStorage("userID", res.data.data.id);
								setLocalStorage("userData", res.data.data);
								setLocalStorage(
									"userName",
									this.userName.trim()
								);
								setLocalStorage("password", md5Psw);
								if (this.checked) {
									setCookie("user", this.userName.trim(), 7);
									setCookie("psw", this.passWord.trim(), 7);
								}
								let str = "";
								console.log('this.path && this.macName', this.path, this.macName);
								if (this.path && this.macName) {
									str = `path=${this.path}&macType=${this.macType}&pltCode=${this.pltCode}&macName=${this.macName}`
								}
								let isVisibleMenu = res.data.data.tMenuWeb.filter(m => m.isVisible == 1);
								// 設備情報はisVisibleが1なら残す。それ以外はpermissXXが1のものだけ残す。
								let filterMenu = isVisibleMenu.filter(m => (m.path === "/BHView") || (m.path !== "/BHView" && res.data.data[m.systemName.toLowerCase()] == 1));
								let defaultPagePath = filterMenu[0].path;
								this.$router.replace(`${defaultPagePath}?${str}`);
							})
							.catch((err) => {
								console.log(err);
								this.loading = false;
							});
					}
				})
				.catch((err) => {
					console.log(err);
					this.loading = false;
				});
			return;
		},
		enterKey(event) {
			const componentName = this.$options.name;
			if (componentName == "Login") {
				const code = event.keyCode
					? event.keyCode
					: event.which
						? event.which
						: event.charCode;
				if (code == 13) {
					this.login();
				}
			}
		},
		enterKeyupDestroyed() {
			document.removeEventListener("keyup", this.enterKey);
		},
		enterKeyup() {
			document.addEventListener("keyup", this.enterKey);
		},
		langChange(type) {
			setCookie("lang", type, 30);
			setLocalStorage("lang", type);
			this.$i18n.locale =
				getLocalStorage("lang") == 1
					? "zh"
					: getLocalStorage("lang") == 0
						? "jp"
						: "en";
			this.lang = getLocalStorage("lang");
		},

		cancelClick() {
			this.showChangePWDDialog = false;
			this.passWord = "";
		},

		changeOrgUserPwdApi() {
			let re = false;
			this.$refs.formLabelAlign.validate((valid) => {
				console.log(valid);
				if (valid) {
					// alert("submit!");
					re = true;
				} else {
					console.log("error submit!!");
					return false;
				}
			});

			if (!re) return;

			let dataJson = {
				account: this.userName.trim(),
				oldPwd: md5(this.passWord.trim()),
				newPwd: this.formLabelAlign.pwd,
				ConfPwd: this.formLabelAlign.checkPass
			};

			changeOrgUserPwd(dataJson).then((res) => {
				if (res.data.code == 0) {
					this.showChangePWDDialog = false;
					this.passWord = "";

					this.$message({
						message: this.$t("message.login.changePwdSuccessTip"),
					});
					return;
				} else {
					this.$alert(res.data.msg, '', {
						confirmButtonText: 'OK',
						type: 'warning',
					});

				}
			});
		},
	},
	// 创建前状态(里面是操作)
	beforeCreate() { },
	// 创建完毕状态(里面是操作)
	created() {
		this.checked = getLocalStorage('userChecked');
		this.userName = getCookie("user");
		// http://localhost:9099/#/?id=5
		// 在组件加载后，您可以通过this.$route.query.id来访问id参数的值

	},
	// 挂载前状态(里面是操作)
	beforeMount() { },
	// 挂载结束状态(里面是操作)
	mounted() {
		removeCookie('token')
		this.path = this.$route.query.path;
		this.macName = this.$route.query.macName;
		this.macType = this.$route.query.macType;
		this.pltCode = this.$route.query.pltCode;
		console.log('this.path', this.path);

		this.enterKeyup();
		getCookie("lang")
			? setLocalStorage("lang", getCookie("lang"))
			: setLocalStorage("lang", "0");
		this.$i18n.locale =
			getLocalStorage("lang") == 1
				? "zh"
				: getLocalStorage("lang") == 0
					? "jp"
					: "en";
		this.lang = getLocalStorage("lang");
		console.log(BASE.IP)
		// this.langChange(0)
		// if (BASE.IP == "http://192.168.33.89:8085") {
		// 	this.langChange(0)
		// } else if (BASE.IP == "https://eng-dev-api.a-mis.com") {
		// 	this.langChange(2)
		// } else if (BASE.IP == "https://demoapi.richtechcn.com") {
		// 	this.langChange(0)
		// }
		this.setDefaultLang();
	},
	// 更新前状态(里面是操作)
	beforeUpdate() { },
	// 更新完成状态(里面是操作)
	updated() { },
	// 销毁前状态(里面是操作)
	beforeDestroy() { },
	// 销毁完成状态(里面是操作)
	destroyed() {
		// 销毁enter事件
		this.enterKeyupDestroyed();
	},
};
</script>

<style lang="scss" scoped>
.Login {
	position: fixed;
	width: 100%;
	height: 100%;
	// background: url("../assets/img/loginBg.png") no-repeat;
	background: #fff;
	background-size: cover;

	.content {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		text-align: center;
	}

	.pic-login-box {
		width: 410px;
		height: 426px;
		background: rgba(226, 233, 242, 0.5);
		border-radius: 3px;
		background: url("../assets/img/login.png") no-repeat;
		background-size: 100% 100%;
		margin: 0 auto;
	}

	.title-pic {
		width: auto;
		height: 34px;
		margin: 0 auto;
		margin-bottom: 12px;
	}

	.msg {
		margin: 0 auto;
		margin-bottom: 28px;
		font-size: 22px;
		font-weight: 600;
		color: rgba(7, 7, 7, 1);
	}

	.title-top {
		font-size: 22px;
		color: rgba(0, 0, 0, 0.85);
		padding: 36px 0 43px 0;
	}

	.ipt {
		width: 346px;
		height: 40px;
		background: rgba(255, 255, 255, 1);
		border-radius: 4px;
		// border: 1px solid rgba(217, 217, 217, 1);
		margin-bottom: 24px;
		color: rgba(0, 0, 0, 0.25);
		font-size: 16px;
	}

	.checkbox-view {
		width: 346px;
		margin: 0 auto;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24px;
	}

	::v-deep .el-checkbox__label {
		font-size: 16px;
		color: rgba(0, 0, 0, 0.65);
	}

	.forget {
		font-size: 14px;
		color: #2667bd;
		cursor: pointer;
	}

	.login-btn {
		width: 346px;
		height: 40px;
		background: rgba(230, 1, 19, 1);
		border-radius: 4px;
		line-height: 40px;
		margin: 0 auto;
		font-size: 16px;
		font-weight: 500;
		color: rgba(255, 255, 255, 1);
		margin-bottom: 24px;
		transition: 0.5s;
	}

	.login-btn:hover {
		box-shadow: 0px 0px 6px 1px rgba(230, 1, 19, 1);
	}

	.lang-view {
		width: 368px;
		text-align: right;
		color: rgba(0, 0, 0, 0.85);
		font-size: 14px;
		margin: 0 auto;

		span {
			cursor: pointer;
		}
	}

	::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
		background-color: #106ebe;
		border-color: #106ebe;
		color: #001529;
	}

	::v-deep .el-checkbox__input.is-indeterminate .el-checkbox__inner {
		background-color: #106ebe;
		border-color: #106ebe;
		color: #001529;
	}

	::v-deep .el-checkbox__inner:hover {
		background-color: #106ebe;
	}

	::v-deep .el-checkbox__inner:hover {
		background-color: #106ebe;
		color: #001529;
	}

	::v-deep .el-checkbox__inner:hover {
		border-color: #106ebe;
	}

	::v-deep .el-loading-spinner i {
		font-weight: bold;
		font-size: 16px;
		color: #fff;
	}

	::v-deep .el-loading-mask {
		box-shadow: 0px 0px 6px 1px rgba(230, 1, 19, 1);
	}
}
</style>
